﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using NewLife.Reflection;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 入库单服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class inbounrdeceiptService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<inbounrdeceipt> _inbounrdeceiptRep;
    private readonly SqlSugarRepository<inventorydetails> _inventorydetailsRep;
    private readonly SqlSugarRepository<warehouselocation> _warehouseLocationRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public inbounrdeceiptService(SqlSugarRepository<inbounrdeceipt> inbounrdeceiptRep, ISqlSugarClient sqlSugarClient, SqlSugarRepository<inventorydetails> inventorydetailsRep, SqlSugarRepository<warehouselocation> warehouseLocationRep)
    {
        _inbounrdeceiptRep = inbounrdeceiptRep;
        _sqlSugarClient = sqlSugarClient;
        _inventorydetailsRep = inventorydetailsRep;
        _warehouseLocationRep = warehouseLocationRep;
    }

    /// <summary>
    /// 分页查询入库单 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询入库单")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<inbounrdeceiptOutput>> Page(PageinbounrdeceiptInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _inbounrdeceiptRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.materialName.Contains(input.Keyword) || u.location.Contains(input.Keyword) || u.comments.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.materialName), u => u.materialName.Contains(input.materialName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.location), u => u.location.Contains(input.location.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.comments), u => u.comments.Contains(input.comments.Trim()))
            .WhereIF(input.materialCode != null, u => u.materialCode == input.materialCode)
            .WhereIF(input.supplierName != null, u => u.supplierName == input.supplierName)
            .WhereIF(input.currentStock != null, u => u.currentStock == input.currentStock)
            .WhereIF(input.inboundQty != null, u => u.inboundQty == input.inboundQty)
            .WhereIF(input.inboundDateRange?.Length == 2, u => u.inboundDate >= input.inboundDateRange[0] && u.inboundDate <= input.inboundDateRange[1])
            .LeftJoin<Partnum>((u, materialCode) => u.materialCode == materialCode.Id)
            .LeftJoin<supplier>((u, materialCode, supplierName) => u.supplierName == supplierName.Id)
            .Select((u, materialCode, supplierName) => new inbounrdeceiptOutput
            {
                Id = u.Id,
                materialCode = u.materialCode,
                materialCodeFkDisplayName = $"{materialCode.PartNumCoding}",
                materialName = u.materialName,
                supplierName = u.supplierName,
                supplierNameFkDisplayName = $"{supplierName.SuppIierName}",
                currentStock = u.currentStock,
                inboundQty = u.inboundQty,
                inboundDate = u.inboundDate,
                qcstatus = u.qcstatus,
                location = u.location,
                comments = u.comments,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取入库单详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取入库单详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<inbounrdeceipt> Detail([FromQuery] QueryByIdinbounrdeceiptInput input)
    {
        return await _inbounrdeceiptRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加入库单 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加入库单")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddinbounrdeceiptInput input)
    {
        var entity = input.Adapt<inbounrdeceipt>();
        inventorydetails inventorydetails = new inventorydetails();
        inventorydetails.materialCode = entity.materialCode;
        inventorydetails.materialName = entity.materialName;
        inventorydetails.materialType = entity.comments;
        inventorydetails.currentStock = entity.currentStock;
        inventorydetails.lastInboundDate = entity.inboundDate;
        inventorydetails.stockStatus = true;

        
        var query = _warehouseLocationRep.AsQueryable()
       .Where(u => u.warehouse_state == "0").ToList();
        var sss = query.FirstOrDefault();
        if (sss != null)
        {
            sss.warehouse_state = "1";

            var sqqs = _warehouseLocationRep.AsUpdateable(sss)
           .ExecuteCommandAsync();
            entity.location = sss.warehouseLocation_code;
            inventorydetails.location = entity.location;
        }
       
        var ax= await _inventorydetailsRep.InsertAsync(inventorydetails) ? inventorydetails.Id : 0;
        return await _inbounrdeceiptRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新入库单 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新入库单")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateinbounrdeceiptInput input)
    {
        var entity = input.Adapt<inbounrdeceipt>();
        await _inbounrdeceiptRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除入库单 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除入库单")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteinbounrdeceiptInput input)
    {
        var entity = await _inbounrdeceiptRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _inbounrdeceiptRep.FakeDeleteAsync(entity);   //假删除
        //await _inbounrdeceiptRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除入库单 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除入库单")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteinbounrdeceiptInput> input)
    {
        var exp = Expressionable.Create<inbounrdeceipt>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _inbounrdeceiptRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _inbounrdeceiptRep.FakeDeleteAsync(list);   //假删除
        //return await _inbounrdeceiptRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDatainbounrdeceiptInput input)
    {
        var materialCodeData = await _inbounrdeceiptRep.Context.Queryable<Partnum>()
            .InnerJoinIF<inbounrdeceipt>(input.FromPage, (u, r) => u.Id == r.materialCode)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.PartNumCoding}"
            }).ToListAsync();
        var supplierNameData = await _inbounrdeceiptRep.Context.Queryable<supplier>()
            .InnerJoinIF<inbounrdeceipt>(input.FromPage, (u, r) => u.Id == r.supplierName)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.SuppIierName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "materialCode", materialCodeData },
            { "supplierName", supplierNameData },
        };
    }
    
    /// <summary>
    /// 导出入库单记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出入库单记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageinbounrdeceiptInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportinbounrdeceiptOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "入库单导出记录");
    }
    
    /// <summary>
    /// 下载入库单数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载入库单数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportinbounrdeceiptOutput>(), "入库单导入模板", (_, info) =>
        {
            if (nameof(ExportinbounrdeceiptOutput.materialCodeFkDisplayName) == info.Name) return _inbounrdeceiptRep.Context.Queryable<Partnum>().Select(u => $"{u.PartNumCoding}").Distinct().ToList();
            if (nameof(ExportinbounrdeceiptOutput.supplierNameFkDisplayName) == info.Name) return _inbounrdeceiptRep.Context.Queryable<supplier>().Select(u => $"{u.SuppIierName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入入库单记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入入库单记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportinbounrdeceiptInput, inbounrdeceipt>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 物料编码
                    var materialCodeLabelList = pageItems.Where(x => x.materialCodeFkDisplayName != null).Select(x => x.materialCodeFkDisplayName).Distinct().ToList();
                    if (materialCodeLabelList.Any()) {
                        var materialCodeLinkMap = _inbounrdeceiptRep.Context.Queryable<Partnum>().Where(u => materialCodeLabelList.Contains($"{u.PartNumCoding}")).ToList().ToDictionary(u => $"{u.PartNumCoding}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.materialCode = materialCodeLinkMap.GetValueOrDefault(e.materialCodeFkDisplayName ?? "");
                            if (e.materialCode == null) e.Error = "物料编码链接失败";
                        });
                    }
                    // 链接 供应商名称
                    var supplierNameLabelList = pageItems.Where(x => x.supplierNameFkDisplayName != null).Select(x => x.supplierNameFkDisplayName).Distinct().ToList();
                    if (supplierNameLabelList.Any()) {
                        var supplierNameLinkMap = _inbounrdeceiptRep.Context.Queryable<supplier>().Where(u => supplierNameLabelList.Contains($"{u.SuppIierName}")).ToList().ToDictionary(u => $"{u.SuppIierName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.supplierName = supplierNameLinkMap.GetValueOrDefault(e.supplierNameFkDisplayName ?? "");
                            if (e.supplierName == null) e.Error = "供应商名称链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<inbounrdeceipt>>();
                    
                    var storageable = _inbounrdeceiptRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.materialName?.Length > 32, "物料名称长度不能超过32个字符")
                        .SplitError(it => it.Item.location?.Length > 32, "存放位置长度不能超过32个字符")
                        .SplitError(it => it.Item.comments?.Length > 32, "备注长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
